import { Outlet, useLocation } from "react-router-dom";
import { Col, Row, Tabs } from "antd";
import { useEffect, useRef, useState } from "react";
import "./index.scss";

export const Content_Antd = () => {
  const location = useLocation();
  const outletRef = useRef<HTMLDivElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);

  const [tabs, setTabs] = useState([]);
  const [activeKey, setActiveKey] = useState("0");
  /**
   * 获取子菜单
   */
  const getTabs = (): any => {
    if (outletRef.current != null) {
      const CN = Array.from(outletRef.current.childNodes);
      if (CN != undefined && CN.length != 0) {
        return CN.filter((item: any) => item.className == "sub-title");
      }
    }
    return [];
  };
  useEffect(() => {
    const h3List = getTabs();
    setTabs(h3List);
    // 更新页签 修改滚动条
    (scrollRef.current as HTMLDivElement).scrollTop = 0;
  }, [location.pathname]);
  const handleScroll = (e) => {
    const scrollTop = e.target.scrollTop;
    let activeIndex = "0";
    const arr: any = [];
    const h3List = getTabs();
    h3List.forEach((item) => {
      arr.push(Math.abs(item.offsetTop - scrollTop));
    });
    activeIndex = arr.indexOf(Math.min(...arr));
    setActiveKey(String(activeIndex));
  };

  useEffect(() => {
    (scrollRef.current as HTMLDivElement).addEventListener(
      "scroll",
      handleScroll,
    );
    return () => {
      if (scrollRef.current) {
        (scrollRef.current as HTMLDivElement).removeEventListener(
          "scroll",
          handleScroll,
        );
      }
    };
  }, []);

  const handlerChange = (activeKey: string) => {
    const element: any = tabs[activeKey];
    const offsetTop = element.offsetTop;
    const parent = document.getElementById("content-parent") as HTMLElement;
    parent.scrollTo({
      top: offsetTop,
      behavior: "smooth",
    });
  };
  return (
    <div ref={scrollRef} id="content-parent" className="content frostedGlass">
      <Row>
        <Col span={19}>
          <div ref={outletRef}>
            <Outlet />
          </div>
        </Col>
        <Col offset={1} span={3}>
          <Tabs
            onChange={handlerChange}
            className="tab"
            activeKey={activeKey}
            tabPosition="right"
            items={tabs.map((item: any, i) => {
              const id = String(i);
              return {
                ...item,
                label: item.innerText,
                key: id,
              };
            })}
          />
        </Col>
      </Row>
    </div>
  );
};
